package com.example.springboot.controller.api;

import com.example.springboot.common.Result;
import com.example.springboot.entity.Comment;
import com.example.springboot.entity.User;
import com.example.springboot.service.ICommentService;
import com.example.springboot.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 评论表 API控制器 - 不需要token验证的API
 * </p>
 *
 * @author
 */
@RestController
@RequestMapping("/api/comment")
public class CommentApi {

    @Resource
    private ICommentService commentService;

    @Resource
    private IUserService userService;

    /**
     * 发表评论
     */
    @PostMapping("/add")
    public Result addComment(@RequestBody Comment comment) {
        return Result.success(commentService.save(comment));
    }

    /**
     * 回复评论
     */
    @PostMapping("/reply")
    public Result replyComment(@RequestBody Comment comment) {
        // 设置当前登录用户

        comment.setUserId(comment.getUserId());

        // 验证父评论是否存在
        Comment parent = commentService.getById(comment.getParentId());
        if (parent == null) {
            return Result.error("400","父评论不存在");
        }

        if (commentService.save(comment)) {
            return Result.success();
        }
        return Result.error("400","回复评论失败");
    }

    /**
     * 获取文章评论列表
     */
    @GetMapping("/list/{articleId}")
    public Result getComments(@PathVariable Integer articleId) {
        // 查询所有评论（包括回复）
        List<Comment> allComments = commentService.lambdaQuery()
                .eq(Comment::getArticleId, articleId)
                .eq(Comment::getStatus,1)
                .orderByAsc(Comment::getTime)
                .list();

        // 查询并设置用户信息
        allComments.forEach(comment -> {
            User user = userService.getById(comment.getUserId());
            if (user != null) {
                comment.setUsername(user.getUsername());
                comment.setNickname(user.getNickname());
                comment.setAvatar(user.getAvatarUrl());
            }
        });

        return Result.success(allComments);
    }
}

